import os
import sys
import json
import django
from django.core.management import call_command


def load_json_data(source_file):
    try:
        print(f'开始导入{source_file}的初始化数据...')
        call_command('loaddata', source_file, verbosity=1)
        print(f'{source_file}数据导入成功！')
    except Exception as e:
        print(f'导入{source_file}数据时发生错误: {str(e)}')
        raise e

def load_initial_data():
    try:
        # 设置Django环境
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lending_index.settings')
        django.setup()
        
        # 导入Django的management命令
        from django.core.management import call_command
        
        # 执行数据库迁移
        print('开始执行数据库迁移...')
        call_command('migrate', verbosity=1)
        print('数据库迁移完成！')
        
        # 导入数据
        query_file = 'query/fixtures/initial_data.json'
        load_json_data(query_file)
        
    except Exception as e:
        print(f'导入数据时发生错误: {str(e)}')
        sys.exit(1)

if __name__ == '__main__':
    load_initial_data()